﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HCQ2_Common.SQL;
using HCQ2_IDAL;
using HCQ2_Model;
using HCQ2_Model.Data;
using HCQ2_Model.Pay;
using HCQ2_Model.ViewModel;

namespace HCQ2_DAL_MSSQL
{
    public partial class N_ShoppingDAL:IN_ShoppingDAL
    {
        /// <summary>
        /// 获取购物车列表
        /// </summary>
        /// <param name="shoppingListParams"></param>
        /// <returns></returns>
        /// <remarks>
        /// 2021-8-2:根据禅道需求ID=147，添加VRType参数处理，查询中有此参数那么添加此参数查询
        /// </remarks>
        public OperationResult<TableModel<List<ShoppingList>>> ShoppingList(ShoppingListParams shoppingListParams)
        {
            int userId = Convert.ToInt32(SqlHelper.ExecuteScalar($"select user_id from T_User where user_guid='{shoppingListParams.userid}'"));

            string sql = string.Format(@"select  
            b.ShoppingId,
            a.file_id CommodityId,
            c.file_url FileImgUrl,
            a.file_name FileName,
            a.alias_name AliasName,
            a.folder_limit FolderLimit,--权限
            a.file_note FileNote,--简介
            case when a.page_type='VRManager' then '素材'
            when a.page_type='VRWorks' then '作品'
            when a.page_type='VRModule' then '组件'
            when a.page_type='VRBuilding' then '楼宇'
            when a.page_type='QDMeta' then '奇点元宇宙'
            when a.page_type='QDMetaProgram' then '应用'
            when a.page_type='QDMetaRoom' then '房间'
            when a.page_type='QDMaterial' then '元宇宙元素'
            when a.page_type='DDCircle' then '度度圈' else '' end PageType,--商品类别            
            case when a.pro_type=1 then 'VRPPT'
            when a.pro_type=2 then '创客'
            when a.pro_type=3 then '头记'
            when a.pro_type=4 then '校史馆' else '' end ProType,--产品类别            
            case when a.page_type='VRManager' then e.code_name
            when a.page_type='VRWorks' then 
            case when a.pro_form=1 then 'VR'
            when a.pro_form=2 then '虚拟仿真'
            when a.pro_form=3 then 'AR' else '' end
            else '' end Format,--格式
            a.create_name CreateFileUser,--作者
            CONVERT(nvarchar(50),a.approve_time,120) ApproveTime,--审核通过时间
            CONVERT(nvarchar(50),a.create_time,120) CreateTime,--时间
            d.ori_price CommodityMoney, --价格
            d.op_month PurchasePeriod, --期限
            d.ori_price Price,--金额
            a.supplyType SupplyType,--是否自营			
            (select CONVERT(nvarchar,MAX(option_size)) from T_DocFileOptions where file_id=a.file_id)+ 'MB' FileSize,
			b.StoreID,--店铺ID
			f.folder_name StoreName,--店铺名称 
			b.Quantity,--商品数量
			b.OrderType, --下单类别
            a.isSoldOut --是否售馨
            from T_DocumentInfo a
            inner join N_Shopping b on a.file_id=b.FileId
            inner join (select * from (select ROW_NUMBER()over(partition by file_id order by create_date desc)rn,* from T_DocBagFileRecord)t where rn=1
            )c on a.file_id=c.file_id
            left join T_VRGoodDisiPrice d on b.FileId=d.file_id and b.PurchasePeriod=d.op_month
            left join T_ItemCodeMenum e on a.mater_type=e.code_value
			left join T_DocumentFolder f on b.StoreID=f.folder_id
            where b.UserId={0}", userId);
            
            //素材
            if (shoppingListParams.VRType != null && shoppingListParams.VRType == 0) 
            {
                sql += " and a.page_type='VRManager'";
            }

            //作品
            if (shoppingListParams.VRType != null && shoppingListParams.VRType == 1)
            {
                sql += " and a.page_type='VRWorks'";
            }
            //组件
            if (shoppingListParams.VRType != null && shoppingListParams.VRType == 2)
            {
                sql += " and a.page_type='VRModule'";
            }
            //度度圈
            if (shoppingListParams.VRType != null && shoppingListParams.VRType == 3)
            {
                sql += " and a.page_type='DDCircle'";
            }
            //楼宇
            //if (shoppingListParams.VRType != null && shoppingListParams.VRType == 5)
            //{
            //    sql += " and a.page_type='VRBuilding'";
            //}
            //元宇宙
            if (shoppingListParams.VRType != null && shoppingListParams.VRType == 4)
            {
                sql += " and a.page_type in ('QDMetaProgram','QDMetaRoom','QDMaterial','VRBuilding')";
            }
            
            
         
            #region 需求《VLions需求规格_度度圈接口需求_订单及购物车-202100909.docx》添加的内容

            //店铺ID
            if (shoppingListParams.StoreID != null)
            {
                sql += " and b.StoreID="+shoppingListParams.StoreID.Value;
            }

            //下单类别
            if (shoppingListParams.OrderType != null)
            {
                sql += " and b.OrderType=" + shoppingListParams.OrderType.Value;
            }

            #endregion


            var listData = SqlHelper.ExecutePageList<ShoppingList>(shoppingListParams.page,shoppingListParams.rows, "CommodityId", sql,false);
            int count = SqlHelper.GetCount(sql);

            #region 禅道170号需求添加 规格列表

            foreach (ShoppingList s in listData) {
                sql = $"select * from N_Spec where SpecType=0 and SpecTypeId={s.ShoppingId}";
                //获取对应的规格信息
                List<SpecParamModel> specParamModels = SqlHelper.ExecuteList<SpecParamModel>(sql);

                //找规格对应的价格
                foreach (SpecParamModel spec in specParamModels) {
                    //规格ID为空直接跳过
                    if (spec.OptionId == null) {
                        continue;
                    }
                    sql = $"select top 1 specMoney from T_VRDDSpecPrice where groupCode in (select groupCode from T_VRDDSpecGroupPrice where fileId={s.CommodityId} and optionID={spec.OptionId})";
                    //商品规格的价格
                    Object obj = SqlHelper.ExecuteScalar(sql);
                    if (obj != null) { 
                        s.Cost = Convert.ToDecimal(obj);
                        //商品规格的总金额
                        s.Amount = s.Cost * s.Quantity;
                        break;
                    }
                }

                s.Specs.AddRange(specParamModels);
            }

            #endregion

            TableModel<List<ShoppingList>> tableModel = new TableModel<List<ShoppingList>>() {
                rows = listData,
                total = count
            };

            return new OperationResult<TableModel<List<ShoppingList>>>(true,"获取购物车列表成功", tableModel);
        }
    }
}
